package com.xinchao.ck_mips.broadcast;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.orhanobut.logger.Logger;
import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.base.CKSubscriber;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.view.PlayActivity;
import com.xinchao.ck_mips.view.SplashActivity;
import com.xinchao.devicemanage.DeviceManager;
import com.xinchao.devicemanage.bean.WatchDogType;
import com.xinchao.devicemanage.constant.DeviceConstant;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by wq on 2019/5/27.
 * 监听应用程序运行状态
 */
public class HomeWatcherService extends Service {
    private static final int CHECK_INTERVAL = (120 * 1000);
    private static final String FRONT_PACKAGE_NAME = "com.xinchao.ck_mips";

    private static final int MESSAGE_ID = 0x1001;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            handler.removeCallbacksAndMessages(null);
            if (isAppIsInBackground()) {
                startMainActivity(false);
            }

            sendMessageDelay(MESSAGE_ID, CHECK_INTERVAL);
        }
    };

    private void startMainActivity(boolean flag) {
        if (TextUtils.isEmpty(ShareUtil.getInstance().getToken()) || flag) {
            Intent newIntent = new Intent(getApplicationContext(), SplashActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(newIntent);
        } else {
            Intent newIntent = new Intent(getApplicationContext(), PlayActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(newIntent);
        }


    }

    @Override
    public void onCreate() {
        super.onCreate();
    }


    private boolean isAppIsInBackground() {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(FRONT_PACKAGE_NAME)) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(FRONT_PACKAGE_NAME)) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && !TextUtils.isEmpty(intent.getStringExtra(AutoLaunchBroadCast.FLAG))) {
            startMainActivity(true);
        } else {
            sendMessageDelay(MESSAGE_ID, CHECK_INTERVAL);
        }

        return START_STICKY;
    }

    public void sendMessageDelay(int message, int delay) {
        if (handler != null) {
            if (handler.hasMessages(message)) {
                handler.removeMessages(message);
            }
        }
        handler.sendEmptyMessageDelayed(message, delay);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO
        return null;
    }

}
